package com.ruoyi.wifiauth.controller;

import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.wifiauth.service.IWifiMiniProgramService;
import com.ruoyi.wifiauth.domain.request.PhoneSubmitRequest;
import com.ruoyi.wifiauth.domain.request.CodeVerifyRequest;
import com.ruoyi.wifiauth.domain.request.CodeResendRequest;
import com.ruoyi.wifiauth.domain.request.AdCompleteRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.time.LocalDateTime;

/**
 * 小程序WiFi认证控制器
 * 处理小程序端的专用接口
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/wifi/auth")
public class WifiMiniProgramController extends BaseController {
    
    private static final Logger log = LoggerFactory.getLogger(WifiMiniProgramController.class);
    
    @Autowired
    private IWifiMiniProgramService wifiMiniProgramService;
    
    /**
     * 提交手机号（广告观看完成后）
     */
    @PostMapping("/phone/submit")
    public AjaxResult submitPhoneNumber(@Valid @RequestBody PhoneSubmitRequest request) {
        try {
            log.info("小程序提交手机号: {}", request);
            
            boolean success = wifiMiniProgramService.completeAdWatch(
                request.getSessionId(), 
                request.getPhoneNumber()
            );
            
            if (success) {
                return success("验证码已发送").put("message", "验证码已发送到您的手机");
            } else {
                return error("发送验证码失败，请重试");
            }
        } catch (Exception e) {
            log.error("提交手机号失败", e);
            return error("系统异常: " + e.getMessage());
        }
    }
    
    /**
     * 验证手机验证码
     */
    @PostMapping("/code/verify")
    public AjaxResult verifyCode(@Valid @RequestBody CodeVerifyRequest request) {
        try {
            log.info("小程序验证码验证: sessionId={}, phone={}, code={}", 
                request.getSessionId(), request.getPhoneNumber(), request.getVerifyCode());
            
            boolean success = wifiMiniProgramService.verifyCodeAndComplete(
                request.getSessionId(), 
                request.getVerifyCode()
            );
            
            if (success) {
                Map<String, Object> networkInfo = new HashMap<>();
                networkInfo.put("ssid", "Free-WiFi");
                networkInfo.put("expireTime", LocalDateTime.now().plusHours(24).toString());
                
                return success("验证成功，网络已开通")
                    .put("authStatus", "success")
                    .put("networkInfo", networkInfo);
            } else {
                return error("验证码错误，请重新输入");
            }
        } catch (Exception e) {
            log.error("验证码验证失败", e);
            return error("系统异常: " + e.getMessage());
        }
    }
    
    /**
     * 重新发送验证码
     */
    @PostMapping("/code/resend")
    public AjaxResult resendVerifyCode(@Valid @RequestBody CodeResendRequest request) {
        try {
            log.info("小程序重发验证码: sessionId={}, phone={}", 
                request.getSessionId(), request.getPhoneNumber());
            
            boolean success = wifiMiniProgramService.resendVerifyCode(
                request.getSessionId(), 
                request.getPhoneNumber()
            );
            
            if (success) {
                return success("验证码已重新发送").put("message", "验证码已重新发送到您的手机");
            } else {
                return error("重新发送失败，请稍后重试");
            }
        } catch (Exception e) {
            log.error("重发验证码失败", e);
            return error("系统异常: " + e.getMessage());
        }
    }
    
    /**
     * 上报广告观看完成
     */
    @PostMapping("/ad/complete")
    public AjaxResult reportAdComplete(@Valid @RequestBody AdCompleteRequest request) {
        try {
            log.info("小程序广告完成上报: {}", request);
            
            boolean success = wifiMiniProgramService.reportAdComplete(
                request.getSessionId(),
                request.getMaterialId(),
                request.getDuration(),
                request.getCompleted(),
                request.getAction()
            );
            
            if (success) {
                return success("广告观看记录已保存");
            } else {
                return error("记录保存失败");
            }
        } catch (Exception e) {
            log.error("广告完成上报失败", e);
            return error("系统异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取服务协议内容
     */
    @GetMapping("/agreements")
    public AjaxResult getAgreements(@RequestParam(value = "type", required = false, defaultValue = "all") String type) {
        try {
            log.info("小程序获取协议内容: type={}", type);
            
            Map<String, Object> agreements = wifiMiniProgramService.getAgreements(type);
            
            return success("获取成功").put("data", agreements);
        } catch (Exception e) {
            log.error("获取协议内容失败", e);
            return error("系统异常: " + e.getMessage());
        }
    }
} 